//
//  WBLoginController.swift
//  SinaMicroblog
//
//  Created by 原鹏飞 on 2017/4/6.
//  Copyright © 2017年 YuanPengFei. All rights reserved.
//

import UIKit

class WBLoginController: UIViewController {
    
    /// webView的懒加载属性
    lazy var webView:UIWebView = {
       let webView = UIWebView(frame: self.view.bounds)
        webView.delegate = self
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.yellow
        
        //设置UI
        setupUI()
        
        //加载数据
        loadLoginPage()
    }
    
    func setupUI() {
        //添加webView
        self.view.addSubview(webView)
        
        //设置返回按钮
        let buttonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(back))
        navigationItem.leftBarButtonItem = buttonItem
    }
    
    func loadLoginPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=1956824072&redirect_uri=http://www.baidu.com"
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
    }
    
    func back() {
        dismiss(animated: true, completion: nil)
    }
}


extension WBLoginController: UIWebViewDelegate {
    
    /// 网页将要加载时执行(如果return true, 则表示request请求成功; 否则失败)
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("@@@@@@@@@@@@@")
        print(request.url?.absoluteString ?? "request请求失败啦")
        
        //1. 判断url是否为回调页, 如果是回调页, 页面不能显示出来, return false
        if let urlString = request.url?.absoluteString, urlString.hasPrefix("http://www.baidu.com") == true, let query = request.url?.query {
            //2. 判断点击的按钮是取消还是授权: 如果参数的前缀是"code=", 说明点击的是授权按钮
            if (query.hasPrefix("code=")) { //点击授权按钮
                /**
                 http://www.baidu.com/?code=0d822614e628ed858c780b4634af6a64
                 range是一个index的区间值(lowerBound..<upperBound), upperBound取的是区间值的右边的index的值; lowerBounds可以取到区间值的左边的index的值
                 */
                //3. 获取code
                //3.1 获取到"code="子串的range
                let subrange = urlString.range(of: "code=")
                //3.2 截取字符串, 获取code
                let code = urlString.substring(from: (subrange?.upperBound)!)
                print("###########")
                print(code)
                //4. 使用code获取token
                NetworkTool.shared.requestToken(code: code, callBack: { (tokenDic) in
                    print("%%%%%%%%%%%%%%")
                    print(tokenDic ?? "获取token失败啦")
                    
                    //顺便获取用户名和头像
                    //判断是否获取到token
                    if let tokenDic = tokenDic as? [String: Any],
                        let uid = tokenDic["uid"] as? String,
                        let token = tokenDic["access_token"] as? String {
                        //5. 获取到token后, 顺便获取用户信息
                        NetworkTool.shared.requestUser(uid: uid, accessToken: token, callBack: { (userDic) in
                            print("$$$$$$$$$$$$$$$$$")
                            print(userDic ?? "获取useDic失败啦")
                            //判断userDic是否有值
                            if var userDic = userDic as? [String: Any]{
                                //6. 合并字典
                                for (k, v) in tokenDic {
                                    userDic[k] = v
                                }
                                
                                //7. 保存用户信息
                                WBUserAccount.shared.save(dict: userDic)
                                
                                //8. 登录成功之后发通知
                                let notification = Notification(name: loginSuccessNotification)
                                NotificationCenter.default.post(notification)
                                
                                self.dismiss()
                            } else {
                                //没有成功获取到user信息
                                self.dismiss()
                            }
                        })
                    } else {
                        //没有成功获取到token
                        self.dismiss()
                    }
                })
            } else {    //点击取消按钮
                self.dismiss()
            }
            return false
        }
        return true
    }
    
    
    func dismiss() {
        dismiss(animated: true, completion: nil)
    }
    

    /// 网页加载成功之后执行
    ///
    /// - Parameter webView: 网页
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //自动填充密码
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='530525714@qq.com';document.getElementById('passwd').value='lsj208660'")
    }
}
